'''
web端
'''


import os

from db.mysql_server import CvvManatukuUser,CvvCardData
from datetime import datetime
from fastapi import FastAPI, UploadFile, File, HTTPException,APIRouter,Depends,BackgroundTasks
from fastapi.responses import JSONResponse
import os
from typing import List, Dict, Any
import tempfile
from utils.cvv_utils import *
from admin import verify_token,get_current_user,UserInfo
from crawler.manat_cvv import do_register

router = APIRouter()


def parse_line(line: str) -> Dict[str, Any]:
    """解析单行数据"""
    line = line.strip()
    if not line or '|' not in line:
        return None

    parts = parse_card_line(line)
    if len(parts) != 3:
        return None
    card_type = detect_card_type(parts[0].strip())

    return {
        'number': parts[0].strip(),
        'month': parts[1].strip(),
        'year': parts[2].strip(),
        'card_type': card_type,
    }


def register(result,user_id,filename):
   do_register(result,user_id,filename)




@router.post("/upload")
async def upload_txt_file(file: UploadFile = File(...),
                          current_user: UserInfo = Depends(get_current_user),
                          background_tasks: BackgroundTasks = BackgroundTasks()
                          ):
    """上传并解析txt文件"""
    # 检查文件类型
    if not file.filename.endswith('.txt'):
        raise HTTPException(status_code=400, detail="只支持txt文件")

    try:
        # 读取文件内容
        content = await file.read()
        text_content = content.decode('utf-8')
        user_id = current_user.user_id
        # 解析内容
        result = parse_text_content(text_content)
        background_tasks.add_task(register,result,user_id,file.filename)
        return {
            "success": True,
            "message": "上传成功开始处理"
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件处理失败: {str(e)}")


def parse_text_content(content: str) -> List[Any]:
    """解析文本内容"""
    parsed_data = []

    lines = content.split('\n')

    for line_num, line in enumerate(lines, 1):
        parsed = parse_line(line)
        if parsed:
            # parsed_data.append({
            #     'line': line_num,
            #     'data': parsed
            # })
            parsed_data.append(parsed)

    return parsed_data


@router.post("/parse-text")
async def parse_text_direct(text: str):
    """直接解析文本内容"""
    result = parse_text_content(text)
    return {
        "success": True,
        "data": result
    }


@router.get("/root")
async def root():
    return {"message": "TXT文件解析API", "version": "1.0.0"}

